(function($) {
    /**
     * 扩展jq，加入增删改查url参数方法
     */
    $.extend({

        del_url_param: function (url, name) {
            var r = url;

            if(!r.match('[\&]+')){
                var reg = new RegExp("[\?]?" + name + "=([^\&]*)", "i");
            }else{
                var reg = new RegExp("[\&]?" + name + "=([^\&]*)", "i");
            }
            if(url.match(reg) != null){
                r = url.replace(eval(reg), '');
            }
            return r;
        },

        put_url_param: function(url, name, value) {
            var r = url;
            if (r != null && r != 'undefined' && r != "") {
                value = encodeURIComponent(value);
                var reg = new RegExp("(^|)" + name + "=([^&]*)(|$)");
                var tmp = name + "=" + value;
                if (url.match(reg) != null) {
                    r = url.replace(eval(reg), tmp);
                } else {
                    if (url.match("[\?]")) {
                        r = url + "&" + tmp;
                    } else {
                        r = url + "?" + tmp;
                    }
                }
            }
            return r;
        },

        get_url_param: function(url, name) {
            var param = url.match(new RegExp("[\?\&]" + name + "=([^\&]*)(\&?)", "i"));
            return param ? param[1] : param;
        },

        get_url_params: function(url) {
            var query = url.split('?');
            var params = new Array;
            if (query.length > 1) {
                let buf = query[1].split('&');
                for (let i = 0; i < buf.length; i++) {
                    let tmp = buf[i].split('=');
                    params.push(tmp);
                }
            }
            return params;
        },

    });

    /**
     * modal确认框
     * 用例：
     *  modal_confirm({
     *      'message': '文字',
     *      'title': '标题',
     *      'bind': function () {
     *          console.log('ok');
     *      }
     *  });
     */
    /*window.modal_confirm = function (param) {
        if($('#confirm_modal').length){ return false; }

        var message = param.message ? param.message : '确认？';
        var title = param.title ? param.title : '标题';
        var bind = param.bind ? param.bind : new Function;

        var modal = `<div class="modal fade" id="confirm_modal">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" data-dismiss="modal" class="close">&times;</button>
                        <h4 class="modal-title">${title}</h4>
                    </div>
                    <div class="modal-body">
                        <p>${message}</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary">确认</button>
                        <button type="button" class="btn btn-info" data-dismiss="modal">关闭</button>
                    </div>
                </div>
           </div>
        </div>`;

        var modal = $(modal).appendTo('body');
        $(modal).modal('show');
        $(modal).on('hidden.bs.modal', function () {
            $(this).remove();
        });

        $(modal).find('.btn-primary').click(bind);
    }*/
})(jQuery);

$(function () {
    // 高度初始化
    function resizeElement() {
        $(".sideMenu").css('min-height', $(document).height());
        $("iframe").css('min-height', $(document).height() - 50);
        // $(".container-admin").css('min-height', $(document).height());
        // $(".container-admin .adminBody").css('min-height', $(document).height() - 50);
    }
    resizeElement();

    // 初始化Messenger
    Messenger.options = {
        extraClasses: 'messenger-fixed messenger-on-bottom',
        theme: 'flat',
        messageDefaults: {
            message: '未知信息',
            type: 'info',
            showCloseButton: true,
            hideAfter: 5
        }
    }

    // 初始化日期选择器
    $(".input-group.date").datepicker({
        format: "yyyy-mm-dd",
        startView: 2,
        todayBtn: "linked",
        language: "zh-CN",
        orientation: "bottom left",
        keyboardNavigation: false,
        forceParse: false,
        autoclose: true,
        todayHighlight: true
    });

    // 初始化日期时间选择器
    $(".form_datetime").datetimepicker({
        language: 'zh-CN',
        format: 'yyyy-mm-dd hh:ii:ss',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        forceParse: 1,
        showMeridian: 0,
        pickerPosition: 'bottom-left'
    });

    // 初始化日期区间选择器
    $('.daterange_picker').daterangepicker({
        'ranges': daterangepicker_range,
        'locale' :daterangepicker_zh_CN,
    });

    // iCheck初始化
    $("input").iCheck({
        checkboxClass: 'icheckbox_square-blue',
        radioClass: 'iradio_square-blue',
        increaseArea: '0%'
    });

    // 触发tooltip
    $('[data-toggle=tooltip]').tooltip();

    // 按键绑定
    $("form").keypress(function (e) {
    	if(e.keyCode == 13){
            $(this).trigger('submit');
        }
    });

    // sideMenu
    $(".collapse_sidebar").click(function (e) {
        $(".sideMenu").toggleClass("sideMenu-collapse");
        $(".sideMenu").toggleClass("sideMenu-open");
        $(".container-admin").toggleClass("admin-collapse");
        $(".container-admin").toggleClass("admin-open");
    });
    $("[data-toggle=openMenu]").click(function (e) {
        if($(this).siblings(".collapsedMenu").css('display') == "block"){
            $(".collapsedMenu").slideUp();
            $(this).siblings(".collapsedMenu").slideUp();
        }else{
            $(".collapsedMenu").slideUp();
            $(this).siblings(".collapsedMenu").slideDown();
        }
    });
    $("[data-href]").click(function () {
        var href = $(this).data('href');
        if(href == '#' || href.match(/javascript[.*]?/i) != null){ return false; }
        $(".sideMenu li").removeClass('active');
        $(this).parent('li').eq(0).addClass('active');
        $("iframe").attr('src', href);
    });

    // adminDropdown
    $("[data-toggle=adminDropdown]").click(function (e) {
        $("#adminDropdown").slideToggle();
        $(this).toggleClass("active");
        e.stopPropagation();
    });
    $(window).click(function (e) {
        if(e.target != $("[data-toggle=adminDropdown]")[0]){
            $("#adminDropdown").slideUp();
            $(".admin_name").removeClass("active");
        }
    });

    // panel
    $('.panel-heading').click(function (e) {
        $(this).siblings('.panel-body').slideToggle();
    });

    // 为分页添加筛选条件
    var source_url = $.get_url_params(window.location.href);
    $('.pagination a').each(function (e) {
        var url = $(this).attr('href');
        for(let i = 0; i < source_url.length; i++){
            if(!source_url[i][0] || source_url[i][0] == 'page'){ continue; }
            url = $.put_url_param(url, source_url[i][0], decodeURIComponent(source_url[i][1]));
        }
        $(this).attr('href', url);
    });

    // 列表通用排序
    $('[data-order]').click(function (e) {
        e.preventDefault();
        var url = window.location.href;
        var order = '';
        if(order = $.get_url_param(url, '_order')){
            order = decodeURIComponent(order).split('|');
            
            var exist = false;
            for(let i = 0; i < order.length; i++){
                if(!order[i]){ continue; }
                order[i] = order[i].split('=');
                if(order[i][0] == $(this).data('order')){
                    exist = true;
                    order[i][1] = order[i][1] == 'asc' ? 'desc' : 'asc';
                }
            }

            if(!exist){ order.push([$(this).data('order'), 'asc']); }

            var tmp = '';
            for(let j = 0; j < order.length; j++){
                if(!order[j]){ continue; }
                tmp += order[j][0] + '=' + order[j][1];
                if(j != (order.length-1)){
                    tmp += '|';
                }
            }
            url = $.put_url_param(url, '_order', tmp);
        }else{
            order = $(this).data('order') + '=asc';
            url = $.put_url_param(url, '_order', order);
        }
        window.location.href = url;
    });

    // 插入排序tag
    var order = $.get_url_param(window.location.href, '_order');
    if(order){
        order = decodeURIComponent(order).split('|');
        for(let i = 0; i < order.length; i++){
            if(!order[i]){ continue; }
            order[i] = order[i].split('=');
            var tag = '<span class="label label-default" data-order-tag="'+order[i][0]+'">';
            tag += $('[data-order='+order[i][0]+']').text()+': ';
            tag += (order[i][1] == 'asc') ? '正序' : '倒序';
            tag += ' &times;</span>';
            tag = $(tag).appendTo('#order_tag');
            
            $(tag).click(function (e) {
                e.preventDefault();
                $(this).remove();

                var url = window.location.href;
                var reg = new RegExp("(\%7C)?" + $(this).data('order-tag') + "\%3D[(asc)|(desc)]+")
                
                if(url.match(reg) != null){
                    url = url.replace(eval(reg), '')
                }
                window.location.href = url;
            });
        }
    }

    // 搜索
    $('#search_form').submit(function (e) {
        e.preventDefault();
        var url = $.del_url_param(window.location.href, '_search');

        var form = $(this).serialize();
        form = form.replace(/\&/g, '|');

        if(url.match(/\?/) != null){
            url += '&_search=' + encodeURIComponent(form);
        }else{
            url += '?_search=' + encodeURIComponent(form);
        }

        window.location.href = url;
    });

    // 通用导出
    $('#export_btn').click(function () {
        var url = window.location.href;
        url = $.put_url_param(url, '_export', '1');
        window.location.href = url;
        // window.open(url,'newwindow','height=300,width=300,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no');
    });
    /*var Export = function (args) {
        $('#export_btn').data('table', args.table);
        $('#export_btn').data('filter', args.filter);
        $('#export_btn').data('key', args.key);
        // 绑定事件
        $('#export_btn').click(function () {
            var _search = $.get_url_param(window.location.href, '_search');
            var _order = $.get_url_param(window.location.href, '_order');

            var table = $(this).data('table');
            var key = $(this).data('key');
            var filter = $(this).data('filter');
            var url = $.put_url_param('/Home/export_excel', 'table', table);
            url = $.put_url_param(url, 'key', key);
            if(_search){ url = $.put_url_param(url, '_search', _search); }
            if(_order){ url = $.put_url_param(url, '_order', _order); }
            if(filter){ url = $.put_url_param(url, '_search_filter', filter); }
            console.log(url);return false;
            window.open(url);
        });
    }

    // 初始化导出类
    new Export({
        table: 'widthdraw',
        filter: 'name',
        key: [
            'id'
        ]
    });*/
});

// 切换按钮loading状态
var btn_form = function (btn) {
    if(!btn){ return false; }
    if($(btn).hasClass('disabled')){
        $(btn).removeClass('disabled');
        $(btn).attr('disabled', false);
        $(btn).html($(btn).data('text'));
        $(btn).data('text', null);
    }else{
        $(btn).addClass('disabled');
        $(btn).attr('disabled', true);
        $(btn).data('text', $(btn).html());
        $(btn).html("<i class='loadingSVG'></i>");
    }
}

// 调用Messenger.post
var post = function (type, msg) {
    var t = 'info';
    switch(type){
        case 1:
            t = 'info';
            break;
        case 2:
            t = 'success';
            break;
        case 3:
            t = 'error';
            break;
    }
    Messenger().post({
        type: t,
        message: msg
    });
}